package job;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

public class Job implements Runnable, Serializable {
	
	public ConcurrentHashMap<String, byte[]> classMap;
	
	public Job() {
		classMap = new ConcurrentHashMap<String, byte[]>();
	}
	
	public boolean addClass(Class<?> c) {
		try {
			String s = c.getName().replace(".", "/") + ".class";
			System.out.println(s);
			
//			InputStream in = c.getResourceAsStream(s);
			
			FileInputStream in = new FileInputStream(s);
			
			if (in == null) {
				System.out.println("in = null");
			}
			
			
			byte single[] = new byte[1];
			Vector<Byte> bytes = new Vector<Byte>();
			while (in.read(single) != -1) {
				bytes.add( new Byte( single[0] ) );
			}
			byte buffer[] = new byte[bytes.size()];
			Iterator<Byte> it = bytes.iterator();
			
			for (int i = 0; it.hasNext(); i ++) {
				buffer[i] = it.next().byteValue();
			}
			System.out.println(c.getName());
			classMap.put(c.getName(), buffer);
			/*  This should work but apparently Classes in memory are not as they appear.
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(baos);
			oos.writeObject(c); oos.flush(); baos.flush();
			classMap.put(c.getName(), baos.toByteArray());
			*/
			return true;
		} catch (IOException e) {
			System.out.println("OH, FUCK!");
		}
		return false;
	}
	
	public void run() {
		
		ClassLoader cl = new HashMapClassLoader(classMap);
		Thread.currentThread().setContextClassLoader(cl);
		System.out.println(Thread.currentThread().getContextClassLoader().getClass().getName());
		try {
			EntryPoint ep = (EntryPoint) Class.forName("sender.Main", true, cl).newInstance();
			String args[] = {"yes", "no"};
			ep.init(args);
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}

}